import Log from './log'

let log = new Log('dp>')

class DelayPromise {
  constructor(debug = false, delay = 100) {
    this._sync = {}
    this._append = {}
    this._delay = delay
    this._debug = debug
  }

  check(key) {
    this._sync.hasOwnProperty(key)
  }

  done(key, error = null, data = null) {
    this._sync[key] = {error: error, data: data}
  }

  genKey(key) {
    return key + '@' + new Date().getTime()
  }

  prepare(key) {
    if (this._debug) {
      log.w('prepare', key)
    }
    delete this._sync[key]
  }

  promise(key) {
    return new Promise((resolve, reject) => {
      let sid = setInterval(_ => {
        if (this._sync.hasOwnProperty(key)) {
          clearInterval(sid)

          const r = this._sync[key]
          delete this._sync[key]

          if (!r.error) {
            resolve(r.data)
            if (this._debug) {
              log.d(key, r.data)
            }
          } else {
            reject(r)
            if (this._debug) {
              log.w(key, r)
            }
          }
        }
      }, this._delay)
    })
  }

  append(key, append) {
    if (this._append.hasOwnProperty(key)) {
      this._append[key].push(append)
    } else {
      this._append[key] = [append]
    }
  }

  appendDone(key, data = null) {
    const append = this._append[key]
    delete this._append[key]

    this._sync[key] = {error: null, data: {data: data, result: append}}
  }

  good(data = null) {
    return new Promise((r, _) => {
      r(data)

      if (this._debug) {
        log.d('good', data)
      }
    })
  }

  bad(reason = null) {
    return new Promise((_, e) => {
      e(reason)

      if (this._debug) {
        log.w('bad', reason)
      }
    })
  }

}

export default DelayPromise;
